import React, { Component } from 'react';
import { Icon, Upload, message } from 'antd';
import http from '@/utils/http';
import { FILE_UPLOAD_URL, VERSION_NO, IMAGE_UPLOAD_SERVICE } from '@/utils/http/config';
import { getBase64 } from '@/utils/common';

class UploadImage extends Component {
  constructor(props) {
    super(props);
    const { value, showFileList } = props;
    this.state = {
      loading: false,
      fileList: showFileList && value ? [{
        uid: '-1',
        status: 'done',
        url: value
      }] : []
    };
  }

  handleCustomRequest({ file }) {
    const { showFileList, onChange, fnOk } = this.props;
    this.setState({ loading: true });
    const formData = new FormData();
    formData.append('type', 'image');
    formData.append('file', file, file.name);
    http.post(FILE_UPLOAD_URL + VERSION_NO + IMAGE_UPLOAD_SERVICE, formData).then(response => {
      if (showFileList) {
        getBase64(file, result => {
          this.setState({
            fileList: [{
              uid: '-1',
              name: file.name,
              status: 'done',
              url: result
            }],
            loading: false
          }, () => {
            // eslint-disable-next-line
            onChange?.(response.data);
            // eslint-disable-next-line
            fnOk?.(response.data);
          });
        });
      } else {
        this.setState({ loading: false });
        // eslint-disable-next-line
        onChange?.(response.data);
        // eslint-disable-next-line
        fnOk?.(response.data);
      }
    });
  }

  handleBeforeUpload(file) {
    const isImage = ['image/jpeg', 'image/png'].includes(file.type);
    if (isImage) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (isLt2M) {
        return true;
      } else {
        message.error('文件必须小于 2MB！');
      }
    } else {
      message.error('您只能上传 JPEG、PNG 文件！');
    }
    return false;
  }

  handleRemove() {
    this.setState({ fileList: [] }, () => {
      // eslint-disable-next-line
      this.props.onChange?.(null);
    });
    return false;
  }

  render() {
    const { text, icon, ...params } = this.props;
    const { loading, fileList } = this.state;
    return (
      <Upload
        className="rs-upload"
        listType="picture-card"
        fileList={fileList}
        showUploadList={{ showPreviewIcon: false }}
        customRequest={this.handleCustomRequest.bind(this)}
        beforeUpload={this.handleBeforeUpload.bind(this)}
        onRemove={this.handleRemove.bind(this)}
        {...params}
      >
        <Icon type={loading ? 'loading' : icon || 'plus'} className="upload-icon" />
        {text ? <div className="upload-text">{text}</div> : ''}
      </Upload>
    );
  }
}

export default UploadImage;
